<template>
  <div class="patient-list-page">
    <div class="toolbar">
      <el-button type="primary" @click="openAddModal">添加患者</el-button>
      <el-button @click="handleExport">导出患者数据</el-button>
      <el-input v-model="search" placeholder="搜索患者姓名/手机号" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch" />
    </div>
    <el-table :data="pagedPatients" style="width: 100%" border @selection-change="handleSelectionChange"
      :row-key="row => row.id" :empty-text="'暂无数据'">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="realName" label="真实姓名"/>
      <!-- <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          <el-tag v-if="row.gender === '男'" type="primary">男</el-tag>
          <el-tag v-else-if="row.gender === '女'" type="danger">女</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80">
        <template #default="{ row }">
          <span>{{ row.age ?? '-' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="phone" label="手机号" width="140">
        <template #default="{ row }">
          <span>{{ row.phone || '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="idCard" label="身份证号" width="180">
        <template #default="{ row }">
          <span>{{ row.idCard || '-' }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="address" label="地址">
        <template #default="{ row }">
          <span>{{ row.address || '-' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <span style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="val => handleStatusChange(row, val)"
              size="small"
            />
            <el-tag v-if="row.status === 1" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="row.status === 0" type="info" size="small">禁用</el-tag>
            <span v-else>-</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="权限" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.role === 'PATIENT'" type="">患者</el-tag>
          <el-tag v-else-if="row.role === 'ADMIN'" type="warning">管理员</el-tag>
          <el-tag v-else-if="row.role === 'DOCTOR'" type="primary">医生</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="170">
        <template #default="{ row }">
          <span>{{ row.createTime ? row.createTime.replace('T', ' ') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="170">
        <template #default="{ row }">
          <span>{{ row.updateTime ? row.updateTime.replace('T', ' ') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openEditModal(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="goDetail(row)">详情</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="filteredPatients.length"
        :page-size="pageSize" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 统一的添加/编辑模态框 -->
    <el-dialog :title="modalTitle" v-model="modalVisible" width="500px" @close="resetModal">
      <el-form :model="modalForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="modalForm.username" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="modalForm.gender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="modalForm.age" type="number" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="modalForm.phone" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="modalForm.idCard" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="modalForm.address" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="modalForm.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="modalForm.role" placeholder="请选择">
            <el-option label="患者" value="PATIENT" />
            <el-option label="医生" value="DOCTOR" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="handleModalOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserListApi, addUserApi, updateUserApi } from '@/api/user.ts'

interface Patient {
  id: number
  username: string
  gender: string
  age: number
  phone: string
  idCard: string
  address: string
  status: number
  role: string
  createTime: string
  updateTime: string
}

const patients = ref<Patient[]>([
])
onMounted(async () => {
  try {
    const res = await getUserListApi()
    if (res && res.data) {
      patients.value = res.data
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
})
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selected = ref<Patient[]>([])

const modalVisible = ref(false)
const modalForm = ref<any>({})
const editingId = ref<number | null>(null)
const modalTitle = computed(() => editingId.value ? '编辑患者' : '添加患者')

const filteredPatients = computed(() => {
  if (!search.value) return patients.value
  const s = search.value.trim().toLowerCase()
  return patients.value.filter(p =>
    p.name.includes(s) ||
    p.phone.includes(s)
  )
})
const pagedPatients = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredPatients.value.slice(start, start + pageSize.value)
})
const router = useRouter()

function handleSearch() {
  currentPage.value = 1
}
function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}
function handleCurrentChange(page: number) {
  currentPage.value = page
}
function handleSelectionChange(val: Patient[]) {
  selected.value = val
}
function openAddModal() {
  editingId.value = null
  modalForm.value = { name: '', gender: '', age: '', phone: '', idCard: '', address: '', status: 1, role: 'PATIENT' }
  modalVisible.value = true
}
function openEditModal(row: Patient) {
  editingId.value = row.id
  modalForm.value = { ...row }
  modalVisible.value = true
}
async function handleModalOk() {
  console.log(modalForm.value)
  if (!modalForm.value.username || !modalForm.value.gender || !modalForm.value.phone) {
    ElMessage.warning('请填写姓名、性别和手机号')
    return
  }
  if (editingId.value) {
    // 编辑
    const res = await updateUserApi({
      id: editingId.value,
      ...modalForm.value
    });
    if (res && res.code === 200) {
      // 更新列表中的数据
      const index = patients.value.findIndex(p => p.id === editingId.value);
      if (index !== -1) {
        patients.value[index] = { ...modalForm.value } as Patient;
      }
      ElMessage.success('更新成功');
    } else {
      ElMessage.error(res?.msg || '更新失败');
    }
  } else {
    // 添加
    const res = await addUserApi({ ...modalForm.value })
    if (res && res.code === 200) {
      const newPatient = {
          ...modalForm.value
        } as Patient;
        patients.value.push(newPatient);
        ElMessage.success('添加成功')
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  }
  modalVisible.value = false
}
function resetModal() {
  editingId.value = null
  modalForm.value = { name: '', gender: '', age: '', phone: '', idCard: '', address: '', status: 1, role: 'PATIENT' }
}
function handleDelete(row: Patient) {
  ElMessageBox.confirm(`确定要删除患者 ${row.name} 吗？`, '提示', { type: 'warning' })
    .then(() => {
      patients.value = patients.value.filter(p => p.id !== row.id)
      ElMessage.success('删除成功')
    })
}
function handleExport() {
  // 简单导出为CSV
  const header = '姓名,性别,年龄,手机号,身份证号,地址\n'
  const rows = selected.value.length ? selected.value : patients.value
  const content = rows.map(p => `${p.name},${p.gender},${p.age},${p.phone},${p.idCard},${p.address}`).join('\n')
  const blob = new Blob([header + content], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'patients.csv'
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}
function goDetail(row: Patient) {
  router.push(`/admin/patient/${row.id}`)
}
</script>
<style scoped>
.patient-list-page {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 18px;
}

.search-input {
  width: 260px;
}

.pagination {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
}
</style>